<!-- 新增和编辑弹窗 -->
<template>
  <a-modal
    :width='800'
    :visible='visible'
    :confirm-loading='loading'
    :title="isUpdate ? '修改' : '新建'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible='updateVisible'
    @ok='putVersion'
  >
    <a-form
      layout='horizontal'
      ref='form'
      :model='form'
      :rules='rules'
      :label-col='{ md: { span: 4 }, sm: { span: 24 } }'
      :wrapper-col='{ md: { span: 20 }, sm: { span: 24 } }'
    >
      <a-form-item label='当前版本:' name='clientVersion'>
        <a-input-number v-model:value='clientVersion' :disabled='true' allow-clear autocomplete='off' />
      </a-form-item>

      <a-form-item label="所属目标版本:" name="upgradeTo">
        <a-select
          show-search
          v-model:value="form.upgradeTo"
          placeholder="请选择所属目标版本"
          style="width: 100%"
          :show-arrow="false"
          :filter-option="false"
          :not-found-content="null"
        >
          <a-select-option v-for="item in firmwareList" :key="item.firmwareId" >
            升级到版本：{{ item.firmwareVersion }}
          </a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script>
import { DeviceRecordApi } from '@/api/property/DeviceRecordApi';
import {DeviceCommandDownQueueApi} from '@/api/property/DeviceCommandDownQueueApi';
import { message } from 'ant-design-vue';
import {DeviceRollershadesUpgradeApi} from "@/api/property/rollershades/DeviceRollershadesUpgradeApi";
import {DeviceRollershadesFirmwareApi} from "@/api/property/rollershades/DeviceRollershadesFirmwareApi";

export default {
  name: 'DeviceRollershadesFirmwareUpgradeEdit',
  components: {
  },
  emits: ['done', 'update:visible'],
  props: {
    // 弹窗是否打开
    visible: Boolean,
    // 修改回显的数据
    data: Object,
    deviceRecord : Object
  },
  created() {
    if (this.data) {
      this.form = Object.assign({}, this.data);
      this.isUpdate = true;
    } else {
      this.form = {};
      this.form.recordId = this.deviceRecord.recordId;
      this.isUpdate = false;
    }
    DeviceRecordApi.detail({"recordId" : this.deviceRecord.recordId}).then(data => {
      this.clientVersion = data.clientVersion;
    });
  },
  async mounted() {
    let firmwareList = await DeviceRollershadesFirmwareApi.list({})
    this.firmwareList = (firmwareList ? firmwareList.data : null) || [];
  },
  data() {
    return {
      // 表单数据
      form: Object.assign({}, this.data),
      // 表单验证规则
      rules: {

      },
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
      firmwareList : [],
      clientVersion : ''
    };
  },
  methods: {
    putVersion()
    {
      let workerDetailparams = {
        recordId: this.deviceRecord.recordId,
        sceneDictate: 5
      };
      let that = this;
      let existWorkerResult = DeviceCommandDownQueueApi.workingDetail2(workerDetailparams);
      existWorkerResult
        .then(workResult => {
          console.log(workResult);
          if (!workResult || !workResult.dcdqId) { //处理完成了
            that.save();
          } else {
            message.error('上一个配置还在推送中，请稍后重试');
            return;
          }
        })
        .catch((e) => {
          message.error(e);
        });
    },
    /**
     * 保存和编辑
     *
     * @author cancan
     * @date 2022/04/03 18:31
     */
    async save() {
      let that = this;
      console.log(this.form);
      // 校验表单
      //await this.$refs.form.validate();
      if (!this.form.upgradeTo) {
        message.error('请选择要升级的版本');
        return;
      }

      // 修改加载框为正在加载
      this.loading = true;

      let result = null;

      // 执行编辑或修改
      if (this.isUpdate) {
        result = DeviceRollershadesUpgradeApi.edit(this.form);
      } else {
        result = DeviceRollershadesUpgradeApi.add(this.form);
      }
      result
        .then(result => {
          console.log(result);
          // 提示添加成功
          message.success(result.message);

          // 如果是新增，则form表单置空
          if (!that.isUpdate) {
            that.form = {};
          }

          //发个命令进行升级
          let updateDataRecord = {
            recordId: that.deviceRecord.recordId,
            templateCode: 'rollershades',
            updateData: JSON.stringify({ old: '', update: ''}),
            dictate : 5,
            sceneDictate : 5
          };

          DeviceCommandDownQueueApi.add(updateDataRecord).then(result1 => {
            console.log(result1);
            that.loading = false;
            // 关闭弹框，通过控制visible的值，传递给父组件
            that.updateVisible(false);
            // 触发父组件done事件
            that.$emit('done');
          }).catch((err) => {
            that.loading = false;
            console.log(err)
          });
        })
        .catch(() => {
          that.loading = false;
        });
    },

    /**
     * 更新编辑界面的弹框是否显示
     *
     * @param value true-显示，false-隐藏
     * @author cancan
     * @date 2022/04/03 18:31
     */
    updateVisible(value) {
      this.$emit('update:visible', value);
    }
  }
};
</script>
